

package org.cscarioni

class SprintController {
    
	static navigation = [
	                     	[action:'edit', title: 'Edit Sprint', order: 1],
							[action:'showPanelForSprint', title: 'Panel', order: 2]
	                    ]
	def index = { redirect(action:list,params:params) }
	def authenticateService;
    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def list = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        [ sprintInstanceList: Sprint.list( params ), sprintInstanceTotal: Sprint.count() ]
    }

    def show = {
        def sprintInstance = Sprint.get( params.id )

        if(!sprintInstance) {
            flash.message = "Sprint not found with id ${params.id}"
            redirect(action:list)
        }
        else { return [ sprintInstance : sprintInstance ] }
    }

    def delete = {
        def sprintInstance = Sprint.get( params.id )
        if(sprintInstance) {
            try {
                sprintInstance.delete(flush:true)
                flash.message = "Sprint ${params.id} deleted"
                redirect(action:list)
            }
            catch(org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "Sprint ${params.id} could not be deleted"
                redirect(action:show,id:params.id)
            }
        }
        else {
            flash.message = "Sprint not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def edit = {
        def sprintInstance = null
		if(params.id){
		  sprintInstance=Sprint.get( params.id )
		}
		else{
			sprintInstance=session.sprint
		}
        if(!sprintInstance) {
            flash.message = "Sprint not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            return [ sprintInstance : sprintInstance ]
        }
    }

    def update = {
        def sprintInstance = Sprint.get( params.id )
        if(sprintInstance) {
            if(params.version) {
                def version = params.version.toLong()
                if(sprintInstance.version > version) {
                    
                    sprintInstance.errors.rejectValue("version", "sprint.optimistic.locking.failure", "Another user has updated this Sprint while you were editing.")
                    render(view:'edit',model:[sprintInstance:sprintInstance])
                    return
                }
            }
            sprintInstance.properties = params
            if(!sprintInstance.hasErrors() && sprintInstance.save()) {
                flash.message = "Sprint ${params.id} updated"
                redirect(action:show,id:sprintInstance.id)
            }
            else {
                render(view:'edit',model:[sprintInstance:sprintInstance])
            }
        }
        else {
            flash.message = "Sprint not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def create = {
        def sprintInstance = new Sprint()
        sprintInstance.properties = params
        return ['sprintInstance':sprintInstance]
    }

    def save = {
        def sprintInstance = new Sprint(params)
        if(!sprintInstance.hasErrors() && sprintInstance.save()) {
            flash.message = "Sprint ${sprintInstance.id} created"
            redirect(action:show,id:sprintInstance.id)
        }
        else {
            render(view:'create',model:[sprintInstance:sprintInstance])
        }
    }
	
	def findByProjectId ={
		def project = Project.get(params.projectId)
		this.session.project=project
    	def sprints = Sprint.findAllByProject(project)
		render (view:'sprintSelect',model:[sprints: sprints,project:Project.get(params.projectId)])
	}
	def createSprintForExistingProject={
		def sprints = Sprint.findAllByProject(Project.get(params.project.id))
		def sprint =new Sprint(params)
		sprint.name=sprints.size()+1
		sprint.panel=new Panel()
		sprint.startDate=new Date()
		sprint.endDate=(new Date() + 21)
		if(!sprint.hasErrors() && sprint.save()){
			sprints = Sprint.findAllByProject(Project.get(params.project.id))
		}		
		render (view:'sprintSelect',model:['sprints': sprints,'project':Project.get(params.project.id)])
	}
	
	def showPanelForSprint ={
    	def sprint = Sprint.get(params.sprintId)
    	def userAuthenticated=authenticateService.userDomain()		
		if(!sprint){
			sprint=session.sprint
		}
		setSprintInUserPreferences(userAuthenticated,sprint)
		def user = getUserFromIdOrAuthenticated(params.userId)		
		this.session.sprint=sprint
		render(view:'panel',model:['sprint':sprint,'user':user])
	}
    def setSprintInUserPreferences(user,sprint){
		user=User.get(user.id)
		if(!user.preferences){
			user.preferences=new UserPreferences()
		}
		user.preferences.preferredSprint=sprint
		user.preferences.save()
		user.save()
    }
    def tableView ={
    	def sprint = Sprint.get(params.sprintId)
		if(!sprint){
			sprint=session.sprint
		}
		def user=getUserFromIdOrAuthenticated(params.userId)
    	this.session.sprint=sprint
		render(view:'panelInTable',model:['sprint':sprint,'user':user])
	}
	def getUserFromIdOrAuthenticated (userId){
		
		def user=null
		def userAuthenticated=authenticateService.userDomain()
		if(params.userId){
			user=User.get(params.userId)
		}
		else{
			user=userAuthenticated
			user=User.get(user.id)
		}
		return user
	}
}
